package com.heima.search.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ArticleSearchService;
import com.heima.search.service.SearchHistoryService;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author jack
 * @data 2024 16:33
 */
@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private SearchHistoryService searchHistoryService;

    /**
     * app文章搜索
     *
     * @param userSearchDto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto userSearchDto) {
        try {

            //开启异步调用：保存用户搜索历史记录
            ApUser apUser = AppThreadLocalUtil.getUser();
            if (apUser != null && apUser.getId() != 0){
                searchHistoryService.saveHistory(userSearchDto.getSearchWords(),apUser.getId());
            }


            //1. 创建一个查询请求，查询索引库: app_info_article
            SearchRequest searchRequest = new SearchRequest("app_info_article");
            //2. 封装请求体参数
            //2.1 设置query请求条件
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
            boolQuery.must(QueryBuilders.multiMatchQuery(userSearchDto.getSearchWords(),"title","content"));
            boolQuery.filter(QueryBuilders.rangeQuery("publishTime").lte(userSearchDto.getMinBehotTime()));
            searchRequest.source().query(boolQuery);

            //2.2 设置分页条件
            searchRequest.source().from(userSearchDto.getFromIndex());
            searchRequest.source().size(userSearchDto.getPageSize());

            //2.3 设置排序条件
            searchRequest.source().sort("publishTime", SortOrder.DESC);

            //2.4 设置高亮属性
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("title").preTags("<font style='color: red; font-size: inherit;'>").postTags("</font>");
            searchRequest.source().highlighter(highlightBuilder);

            //3. 发送查询请求
            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

            //4. 解析响应结果，返回给前端
            SearchHit[] hits = response.getHits().getHits();
            List<JSONObject> list = new ArrayList<>();
            for (SearchHit hit : hits) {
                String sourceAsString = hit.getSourceAsString();
                JSONObject articleVo = JSONObject.parseObject(sourceAsString);
                //处理标题：将key由 title 改成 h_title
                //说明：当标题有highlight时，需要取highlight中的title，如果没有，则取source中的title
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if (highlightFields == null || highlightFields.size() ==0){
                    articleVo.put("h_title",articleVo.getString("title"));
                }else{
                    //有highlight时，需要取highlight中的title
                    String hTitle= highlightFields.get("title").getFragments()[0].toString();
                    articleVo.put("h_title",hTitle);
                }

                list.add(articleVo);
            }

            return ResponseResult.okResult(list);


        }catch (Exception e){
            e.printStackTrace();
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }
}
